package com.siwei.mes.service.system.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.entity.system.UserCertificate;
import com.siwei.mes.entity.system.Warning;
import com.siwei.mes.entity.vo.CertificateTimeInfoVo;
import com.siwei.mes.enums.WarningEnum;
import com.siwei.mes.mapper.system.UserCertificateMapper;
import com.siwei.mes.mapper.system.UserMapper;
import com.siwei.mes.mapper.system.WarningMapper;
import com.siwei.mes.service.system.UserCertificateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 用户证书(UserCertificate)表服务实现类
 *
 * @author linzi
 * @since 2024-07-16 14:38:50
 */
@Service
public class UserCertificateServiceImpl implements UserCertificateService {
    @Resource
    private UserCertificateMapper userCertificateMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WarningMapper warningMapper;

    @Override
    public Long create(UserCertificate entity) {
        assertTrue(userMapper.selectByPrimaryKey(entity.getUserId()) == null, "用户信息不存在");
        UserCertificate isExist = this.checkIsExist(entity);
        assertTrue(isExist != null, "该用户已存在此证书");
        entity.init(true);
        userCertificateMapper.insertSelective(entity);
        return entity.getId();
    }

    /**
     * 判断该用户是否存在此证书
     *
     * @param entity
     * @return
     */
    private UserCertificate checkIsExist(UserCertificate entity) {
        UserCertificate select = new UserCertificate().setUserId(entity.getUserId()).setCertificateNo(entity.getCertificateNo());
        return userCertificateMapper.selectOne(select);
    }

    @Override
    public void update(UserCertificate entity) {
        UserCertificate userCertificate = userCertificateMapper.selectByPrimaryKey(entity.getId());
        assertTrue(userCertificate == null, "用户证书信息不存在");

        assertTrue(userMapper.selectByPrimaryKey(entity.getUserId()) == null, "用户信息不存在");

        if (!entity.getCertificateNo().equals(userCertificate.getCertificateNo())) {
            UserCertificate isExist = this.checkIsExist(entity);
            assertTrue(isExist != null, "该用户已存在此证书");
        }
        entity.init(false);
        userCertificateMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        UserCertificate userCertificate = userCertificateMapper.selectByPrimaryKey(id);
        assertTrue(userCertificate == null, "用户证书信息不存在");
        userCertificateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<UserCertificate> getPage(PageQuery<UserCertificate, UserCertificate> query) {
        UserCertificate searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> userCertificateMapper.getList(searchParam));
    }

    @Override
    public UserCertificate loadById(Long id) {
        return userCertificateMapper.loadById(id);
    }

    @Override
    public List<UserCertificate> getAll(UserCertificate entity) {
        List<UserCertificate> list = userCertificateMapper.getList(entity);
        for (UserCertificate certificate : list) {
            /**处理预警状态*/
            this.payloadWarningStatus(certificate);
        }
        return list;
    }

    /**
     * 处理预警状态
     *
     * @param certificate 用户证书
     */
    private void payloadWarningStatus(UserCertificate certificate) {
        Warning warning = warningMapper.selectByWarningCode(WarningEnum.CERTIFICATE.getCode());
        if (warning == null || warning.getWarningTime() <= 0) {
            return;
        }
        Integer warningTime = warning.getWarningTime();//预警天数
        certificate.setPeibi(this.computeStatus(certificate.getPeibi(), warningTime));//配比
        certificate.setTongcao(this.computeStatus(certificate.getTongcao(), warningTime));//砼操
        certificate.setShuini(this.computeStatus(certificate.getShuini(), warningTime));//水泥
        certificate.setGuliao(this.computeStatus(certificate.getGuliao(), warningTime));//骨料
        certificate.setShajiang(this.computeStatus(certificate.getShajiang(), warningTime));//砂浆
        certificate.setGuanli(this.computeStatus(certificate.getGuanli(), warningTime));//管理
        certificate.setShebei(this.computeStatus(certificate.getShebei(), warningTime));//设备
        certificate.setWangguan(this.computeStatus(certificate.getWangguan(), warningTime));//网管
        certificate.setWaican(this.computeStatus(certificate.getWaican(), warningTime));//外掺
        certificate.setHuaxue(this.computeStatus(certificate.getHuaxue(), warningTime));//化学
        certificate.setGangjin(this.computeStatus(certificate.getGangjin(), warningTime));//钢筋
        certificate.setGoujian(this.computeStatus(certificate.getGoujian(), warningTime));//构件
    }

    /**
     * 计算预警状态   预警状态  0-正常 1-预警 2-过期
     *
     * @param jsonObject
     * @param warningTime
     * @return
     */
    private JSONObject computeStatus(JSONObject jsonObject, Integer warningTime) {
        if (jsonObject.isEmpty()) {
            return jsonObject;
        }
        CertificateTimeInfoVo timeInfoVo = JsonUtils.getObject(jsonObject, CertificateTimeInfoVo.class);

        if (timeInfoVo == null) {
            return jsonObject;
        }
        timeInfoVo.setWarningStatus(0);//默认设置为正常
        if (StringUtils.isBlank(timeInfoVo.getEndTime())) {
            return JsonUtils.beanToObject(timeInfoVo);
        }
        Date now = DateHelper.parseDate(DateHelper.getCurrentDate());
        Date endTime = DateHelper.parseDate(timeInfoVo.getEndTime());
        /**如果当前时间大于证书时间  说明就过期了*/
        if (now.getTime() > endTime.getTime()) {
            timeInfoVo.setWarningStatus(2);
            return JsonUtils.beanToObject(timeInfoVo);
        }

        /**当前时间-证书结束时间  小于等于预警天数  则预警*/
        long daysBetween = DateHelper.daysBetween(now, endTime);
        if (daysBetween <= warningTime) {
            timeInfoVo.setWarningStatus(1);
            return JsonUtils.beanToObject(timeInfoVo);
        }
        return JsonUtils.beanToObject(timeInfoVo);
    }
}
